# -*- coding: utf-8 -*-

import json

try:
    # Pytnon 3
    from socketserver import BaseRequestHandler
except:
    # Pytnon 2
    from SocketServer import BaseRequestHandler
    bytes = str

try:
    str = unicode
except:
    pass

from jsonrpc.sendmsg import max_packet_size

class JsonMsgTcpRequestHandler(BaseRequestHandler):
    """
    Accepts only jsonable string data
    And sends too...
    
    Reimplement _json_handle method!
    """
    
    def _json_handle(self, json_data):
        """
        @param json_data: simple object data, after json.loads
        @type: mixed
        
        @return: python simple object data, jsonable via json.dumps
        @rtype: mixed
        """
        raise NotImplementedError("Method _json_handle must be implemented in %s" % self.__class__.__name__)
    
    def handle(self):
        # self.request is the TCP socket connected to the client
        sock = self.request
        
        data = []
        done = False
        while not done:
            try:
                chunk = sock.recv(max_packet_size)
            except:
                chunk = ""
            
            chunk_length = len(chunk)
            if not chunk_length or chunk_length < max_packet_size:
                done = True
            data.append( chunk )
        
        data = "".join(data)
        
        # just send back the same data, but upper-cased
        data = json.loads(data)
        data = self._json_handle(data)
        data = json.dumps(data) + "\n"
        
        self.request.send(data)
        return
    
    pass

class JsonMsgUdpRequestHandler(BaseRequestHandler):
    """
    Accepts only jsonable string data
    And sends too...

    Reimplement _json_handle method!
    """

    def _json_handle(self, json_data):
        """
        @param json_data: simple object data, after json.loads
        @type: mixed

        @return: python simple object data, jsonable via json.dumps
        @rtype: mixed
        """
        raise NotImplementedError("Method _json_handle must be implemented in %s" % self.__class__.__name__)

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]

        try:
            # print("JsonMsgUdpRequestHandler: data=%r" % (data,))
            # just send back the same data, but upper-cased
            data = json.loads(data.decode("utf-8"))
            data = self._json_handle(data)
            data = json.dumps(data)
        except Exception as e:
            import traceback
            print("JsonMsgUdpRequestHandler: %r\n%s" % (e, traceback.format_exc()))
            data = ""

        socket.sendto(data.encode("utf-8"), self.client_address)
        return

    pass


RequestHandler = JsonMsgUdpRequestHandler